package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.UserService;
import com.csi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/findByIdController")
public class FindByIdController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserService userService = new UserServiceImpl();
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();

        int userId = Integer.parseInt(req.getParameter("userId"));
        User user = null;

        try {
            user = userService.findById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            Result<Object> result = new Result<>();
            result.setCode(500);
            result.setMsg("服务器内部错误");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        if (user == null) {
            Result<Object> result = new Result<>();
            result.setCode(404);
            result.setMsg("用户不存在");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        Result<User> result = new Result<>();
        result.setCode(200);
        result.setMsg("success");
        result.setDatas(user);

        out.print(JSON.toJSONString(result));

        out.flush();
        out.close();
    }
}

